import logging
import qrcode
import base64
import os
from io import BytesIO
from odoo import api, fields, models
from PIL import Image,ImageFont,ImageDraw
from odoo import tools, _
from odoo.exceptions import ValidationError, AccessError
from odoo.modules.module import get_module_resource
import json
_logger = logging.getLogger(__name__)

class InheritPosConfig(models.Model):
    _inherit = 'restaurant.table'

    config_id = fields.Many2one("pos.config", _("Belongs To POS"), readonly= True, default=lambda self: self.env.user.config_id)
    # 二维码
    image_show = fields.Binary(u'QR Code', compute='_compute_config_id')
    # 二维码下载
    image_download = fields.Binary(u'QR Code Download', compute='_compute_config_id')
    # 二维码下载
    qrcode_name = fields.Char(string=_('QR Code Download'), compute='_compute_qrcode_name')

    @api.depends("name", "config_id")
    def _compute_qrcode_name(self):
        for l in self:
            if l.id != False and l.config_id != False:
                l.qrcode_name = str(l.config_id.name) + "-" + str(l.name) + ".png"

    @api.depends("name", "config_id")
    def _compute_config_id(self):
        for l in self:
            if isinstance(l.id,int) != False and isinstance(l.config_id.id,int) != False:
                strdic = {"id":l.id,"name": l.name, "config_id": l.config_id.id}
                _logger.info("------------im，%s----------------", str(l.id))
                qr_code = qrcode.QRCode(version=4, box_size=4, border=1)
                qr_code.add_data(json.dumps(strdic))
                qr_code.make(fit=True)
                qr_img = qr_code.make_image()
                im = qr_img._img.convert("RGB")
                ims = im.resize((240, 240))
                image_haed = Image.new('RGB', (240, 60), (255, 255, 255))
                font = ImageFont.truetype(os.path.dirname(__file__)+'/simkai.ttf', 20)
                draw = ImageDraw.Draw(image_haed)
                draw.text(((240 - len(str(l.config_id.name)) * 22) / 2, 10), str(l.config_id.name), font=font,
                          fill=(0, 0, 0))

                image = Image.new('RGB', (240, 60), (255, 255, 255))
                font = ImageFont.truetype(os.path.dirname(__file__)+'/simkai.ttf', 20)
                _logger.info("------------im，%s----------------", str(os.path.dirname(__file__)))
                draw = ImageDraw.Draw(image)
                draw.text(((240 - len( str(l.name)) * 22) / 2, 10), str(l.name), font=font,
                          fill=(0, 0, 0))
                toImage = Image.new('RGBA', (240, 360))
                toImage.paste(image_haed, (0, 0))
                toImage.paste(ims, (0, 60))
                toImage.paste(image, (0, 300))
                byte_io = BytesIO()
                toImage.save(byte_io, 'PNG')
                byte_io.seek(0)
                ls_f = base64.b64encode(byte_io.getvalue())  # 读取文件内容，转换为base64编码
                l.image_show = ls_f
                l.image_download = ls_f